import socket
import os
from cryptography.fernet import Fernet

# 生成密钥
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接到服务器
server_address = ('172.16.219.51', 9999)
client_socket.connect(server_address)

try:
    # 发送密钥到服务器
    client_socket.send(key)

    # 发送文件路径到服务器
    file_path = input("请输入要发送的文件路径：")
    if not os.path.exists(file_path):
        print(f"文件 {file_path} 不存在！")
        client_socket.close()
        exit()

    client_socket.send(file_path.encode('utf-8'))

    # 发送文件大小
    file_size = os.path.getsize(file_path)
    client_socket.send(str(file_size).encode('utf-8'))

    # 接收服务器确认信息
    confirmation = client_socket.recv(1024).decode('utf-8')
    print(f"接收到服务器确认信息：{confirmation}")
    if confirmation != "准备好接收文件":
        print("服务器没有准备好接收文件，传输取消！")
        client_socket.close()
        exit()

    # 发送文件数据
    with open(file_path, 'rb') as file:
        data = file.read(1024)
        while data:
            client_socket.send(data)
            data = file.read(1024)

    print("文件发送完成")

finally:
    # 关闭连接
    client_socket.close()